<?php

// App::uses('Component', 'Controller');

class CustomComponent extends Component {

    /**
     * Controller reference
     *
     * @var Controller
     */
    protected $_controller = null;
    public $queryParams = null;

    /**
     * Constructor
     *
     * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components
     * @param array $settings Array of configuration settings.
     */
    public function __construct(ComponentCollection $collection, $settings = array()) {
        $this->_controller = $collection->getController();
        parent::__construct($collection, $settings);
    }

    /**
     * Initialize component
     *
     * @param Controller $controller Instantiating controller
     * @return void 
     */
    // Resize any specified jpeg, gif, or png image
    // Outputs errors...
///////////////////////////////////////////////////////////////////////////////////////////////////////
    public $name = 'Image';
    private $__errors = array();

    /**
     * Determines image type, calculates scaled image size, and returns resized image. If no width or height is
     * specified for the new image, the dimensions of the original image will be used, resulting in a copy
     * of the original image.
     *
     * @param string $original absolute path to original image file
     * @param string $new_filename absolute path to new image file to be created
     * @param integer $new_width (optional) width to scale new image (default 0)
     * @param integer $new_height (optional) height to scale image (default 0)
     * @param integer $quality quality of new image (default 100, resizePng will recalculate this value)
     *
     * @access public
     *
     * @return returns new image on success, false on failure. use ImageComponent::getErrors() to get an array
     * of errors on failure
     */
    function resize($source_image, $destination_filename, $width = 200, $height = 150, $quality = 100, $crop = false) {

        $extension = end(explode('.', $source_image));
        $extension = strtolower($extension);
        //$new_filename	=	$new_filename.'.'.$extension;

        $destination_filename = $destination_filename . "." . $extension;


        if (!$image_data = getimagesize($source_image)) {
            return false;
        }

        switch ($image_data['mime']) {
            case 'image/gif':
                $get_func = 'imagecreatefromgif';
                $suffix = ".gif";
                break;
            case 'image/jpeg';
                $get_func = 'imagecreatefromjpeg';
                $suffix = ".jpg";
                break;
            case 'image/png':
                $get_func = 'imagecreatefrompng';
                $suffix = ".png";
                break;
        }

        $img_original = call_user_func($get_func, $source_image);
        $old_width = $image_data[0];
        $old_height = $image_data[1];
        $new_width = $width;
        $new_height = $height;
        $src_x = 0;
        $src_y = 0;
        $current_ratio = round($old_width / $old_height, 2);
        $desired_ratio_after = round($width / $height, 2);
        $desired_ratio_before = round($height / $width, 2);

        if ($old_width < $width || $old_height < $height) {
            /**
             * The desired image size is bigger than the original image. 
             * Best not to do anything at all really.
             */
//				 copy($source_image,$destination_filename); 
            //   return false;
        }


        /**
         * If the crop option is left on, it will take an image and best fit it
         * so it will always come out the exact specified size.
         */
        if ($crop) {
            /**
             * create empty image of the specified size
             */
            $new_image = imagecreatetruecolor($width, $height);

            /**
             * Landscape Image
             */
            if ($current_ratio > $desired_ratio_after) {
                $new_width = $old_width * $height / $old_height;
            }

            /**
             * Nearly square ratio image.
             */
            if ($current_ratio > $desired_ratio_before && $current_ratio < $desired_ratio_after) {
                if ($old_width > $old_height) {
                    $new_height = max($width, $height);
                    $new_width = $old_width * $new_height / $old_height;
                } else {
                    $new_height = $old_height * $width / $old_width;
                }
            }

            /**
             * Portrait sized image
             */
            if ($current_ratio < $desired_ratio_before) {
                $new_height = $old_height * $width / $old_width;
            }

            /**
             * Find out the ratio of the original photo to it's new, thumbnail-based size
             * for both the width and the height. It's used to find out where to crop.
             */
            $width_ratio = $old_width / $new_width;
            $height_ratio = $old_height / $new_height;

            /**
             * Calculate where to crop based on the center of the image
             */
            $src_x = floor(( ( $new_width - $width ) / 2 ) * $width_ratio);
            $src_y = round(( ( $new_height - $height ) / 2 ) * $height_ratio);
        }
        /**
         * Don't crop the image, just resize it proportionally
         */ else {
            if ($old_width > $old_height) {
                $ratio = max($old_width, $old_height) / max($width, $height);
            } else {
                $ratio = max($old_width, $old_height) / min($width, $height);
            }

            $new_width = $old_width / $ratio;
            $new_height = $old_height / $ratio;

            $new_image = imagecreatetruecolor($new_width, $new_height);
        }

        /**
         * Where all the real magic happens
         */
        imagecopyresampled($new_image, $img_original, 0, 0, $src_x, $src_y, $new_width, $new_height, $old_width, $old_height);

        /**
         * Save it as a JPG File with our $destination_filename param.
         */
        imagejpeg($new_image, $destination_filename, $quality);

        /**
         * Destroy the evidence!
         */
        //imagedestroy( $new_image );
        //imagedestroy( $img_original );

        /**
         * Return true because it worked and we're happy. Let the dancing commence!
         */
        return $new_image;
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////









    public function setPaginator($options = array()) {
        $defaults = array(
            'page' => isset($_GET['page']) ? intval($_GET['page']) : 1,
            'limit' => 20
        );
        $options = array_merge($defaults, $options);

        $page = $options['page'];
        //$num_results = $options['num_items'];
        $totalrecords = $options['count'];
        $perpage = $options['limit'];

        $pageCount = intval(ceil($totalrecords / $perpage));
        $page = max(min($page, $pageCount), 1);
        //$page = max($pageCount, 1);

        $this->queryParams = array('page' => $page, 'limit' => $perpage, 'offset' => ($page - 1) * $perpage);

        $paging = array(
            'page' => $page,
            //'current' => $num_results,
            'count' => $totalrecords,
            'prevPage' => ($page > 1),
            'nextPage' => ($totalrecords > ($page * $perpage)),
            'pageCount' => $pageCount,
            'order' => null,
            'limit' => $perpage,
            'options' => array(),
            'paramType' => 'get'
                //'paramType'=>'named'
        );

        $this->_controller->params['paging'] = array('Model' => $paging);

        //from PaginatorComponent
        if (!isset($this->_controller->request['paging'])) {
            $this->_controller->request['paging'] = array();
        }
        $this->_controller->request['paging'] = array_merge(
                (array) $this->_controller->request['paging'], array('Model' => $paging)
        );


        if (
                !in_array('Paginator', $this->_controller->helpers) &&
                !array_key_exists('Paginator', $this->_controller->helpers)
        ) {
            $this->_controller->helpers[] = 'Paginator';
        }
    }

}
